import { Button, Table } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { useContext, useEffect, useMemo, useState } from 'react'
import { TableTargetInfo } from '../../data'
import styles from './index.module.less'

import { reportCheckContext } from '../../_context'
import { getTargetValue } from '../../service'
import { isNullArray, isNullData } from '@/utils'

export default () => {
  const { selectWord, varableTableList } = useContext(reportCheckContext)
  // 表格数据
  const [tableList, setTableList] = useState<TableTargetInfo[]>([])
  // 标头
  const [tableHeader, setTableHeader] = useState<ColumnsType<TableTargetInfo>>([])
  const [loading, setLoading] = useState<boolean>(false)

  // 表格数据
  const getTable = async () => {
    setLoading(true)
    const newlist = varableTableList
      .map((item) => item.variablePlatformVos.map((val) => ({ variableId: val.id, variableValue: val.variableValue })))
      .flat()
    const res = await getTargetValue({
      dataId: selectWord!,
      variableValueDtos: newlist,
    })

    if (isNullData(res) && res.data && isNullArray(res.data)) {
      setTableList(res.data.targetValueVos)
      const newlist: ColumnsType<TableTargetInfo> = [
        {
          title: res.data.dataQuarter[0],
          dataIndex: 'lastValue',
          align: 'center',
        },
        {
          title: res.data.dataQuarter[1],
          dataIndex: 'value',
          align: 'center',
        },
      ]
      setTableHeader(newlist)
    } else {
      setTableList([])
    }
    setLoading(false)
  }

  useEffect(() => {
    getTable()
  }, [varableTableList])

  const columns: ColumnsType<TableTargetInfo> = useMemo(
    () => [
      // {
      //   title: '编号',
      //   dataIndex: 'id',
      //   align: 'center',
      // },
      {
        title: '指标',
        dataIndex: 'targetName',
        align: 'center',
      },
      ...tableHeader,
    ],
    [tableHeader],
  )

  return (
    <Table
      loading={loading}
      className={styles.table}
      style={{ marginTop: '24px' }}
      pagination={false}
      columns={columns}
      dataSource={tableList}
      rowKey={'id'}
    />
  )
}
